package com.jzo2o.trade.controller;

import com.jzo2o.trade.service.IRefundService;
import com.wechat.pay.java.core.exception.ValidationException;
import com.wechat.pay.java.core.notification.NotificationConfig;
import com.wechat.pay.java.core.notification.NotificationParser;
import com.wechat.pay.java.core.notification.RequestParam;
import com.wechat.pay.java.service.refund.model.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @Description:
 * @Version: V1.0
 */
@Slf4j
@RestController
@RequestMapping
public class RefundNotifyController {
    @Autowired
    private NotificationConfig notificationConfig;
    @Resource
    private IRefundService refundService;

    @PostMapping("/wxpay/refund/notify")
    public String payNotify(@RequestBody String body, HttpServletRequest request) throws Exception {
        log.info("收到微信回调消息");
        String wechatSignature = request.getHeader("Wechatpay-Signature");
        String wechatPaySerial = request.getHeader("Wechatpay-Serial");
        String wechatpayNonce = request.getHeader("Wechatpay-Nonce");
        String wechatTimestamp = request.getHeader("Wechatpay-Timestamp");
        // 构造 RequestParam
        RequestParam requestParam = new RequestParam.Builder()
                .serialNumber(wechatPaySerial)
                .nonce(wechatpayNonce)
                .signature(wechatSignature)
                .timestamp(wechatTimestamp)
                .body(body)
                .build();
        // 初始化 NotificationParser
        NotificationParser parser = new NotificationParser(notificationConfig);
        try {
            // 以支付通知回调为例，验签、解密并转换成 Transaction
            RefundNotification transaction = parser.parse(requestParam, RefundNotification.class);
            String outRefundNo = transaction.getOutRefundNo();
            log.info("退款成功：{}", outRefundNo);
            //todo
            refundService.refundSuccess(transaction);
        } catch (ValidationException e) {
            // 签名验证失败，返回 401 UNAUTHORIZED 状态码
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).toString();
        }
        // 处理成功，返回 200 OK 状态码
        return ResponseEntity.status(HttpStatus.OK).toString();
    }


}
